package com.qiguliuxing.dts.db.service;

import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.qiguliuxing.dts.db.dao.DtsArticleMapper;
import com.qiguliuxing.dts.db.domain.DtsArticle;

@Service
public class DtsArticleService {

	@Resource
	private DtsArticleMapper articleMapper;

	public DtsArticle findById(Integer id) {
		return articleMapper.selectById(id);
	}

	/**
	 * 需要demo测试
	 */
	public List<DtsArticle> queryList(int offset, int limit, String sort, String order) {
		QueryWrapper<DtsArticle> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("deleted", false);
		queryWrapper.orderByDesc(sort);
		IPage<DtsArticle> iPage = new Page<>(offset, limit);
		iPage = articleMapper.selectPage(iPage, queryWrapper);
		return iPage.getRecords();
	}
	
	public boolean checkExistByTitle(String title) {
		QueryWrapper<DtsArticle> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("title", title);
		queryWrapper.eq("deleted", false);
		return articleMapper.selectCount(queryWrapper) != 0;
	}

	public void add(DtsArticle article) {
		article.setAddTime(LocalDateTime.now());
		article.setUpdateTime(LocalDateTime.now());
		articleMapper.insert(article);
	}

	public List<DtsArticle> querySelective(String title, Integer page, Integer size, String sort, String order) {
		QueryWrapper<DtsArticle> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(title)) {
			queryWrapper.like("title", title);
		}
		queryWrapper.eq("deleted", false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}
		IPage<DtsArticle> iPage = new Page<>(page, size);
		iPage = articleMapper.selectPage(iPage, queryWrapper);
		return iPage.getRecords();
	}

	public int updateById(DtsArticle article) {
		article.setUpdateTime(LocalDateTime.now());
		return articleMapper.updateById(article);
	}

	public void deleteById(Integer id) {
		articleMapper.deleteById(id);
	}
}
